//
//  BEItemView.swift
//  MeiMeiNew
//
//  Created by 王伟 on 2019/5/26.
//  Copyright © 2019 admin. All rights reserved.
//

import UIKit

class BEItemView: UIView {

    fileprivate var menuText: MenuItemText!
    
    fileprivate let titleLabel: UILabel = {
        let label = UILabel(frame: .zero)
        label.numberOfLines = 1
        label.textAlignment = .center
        label.isUserInteractionEnabled = true
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    
    var textWidth: CGFloat {
        get {
            return estimatedLabelSize(self.titleLabel).width
        }
    }
    
    internal init(menuText: MenuItemText) {
        super.init(frame: .zero)
        
        self.menuText = menuText
        setupLabel()
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate func setupLabel() {
        titleLabel.text = menuText.text
        updateLabel(titleLabel, text: menuText)
        addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().offset(-10)
            make.centerX.equalToSuperview()
        }
    }
    
    public internal(set) var isSelected: Bool = false {
        didSet {
            updateLabel(titleLabel, text: menuText)
        }
    }

    fileprivate func updateLabel(_ label: UILabel, text: MenuItemText) {
        label.textColor = isSelected ? text.selectedColor : text.color
        label.font = isSelected ? text.selectedFont : text.font
    }
    
    public func estimatedLabelSize(_ label: UILabel) -> CGSize {
        guard let text = label.text else { return .zero }
        return NSString(string: text).boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [kCTFontAttributeName as NSAttributedString.Key: label.font ?? UIFont.systemFont(ofSize: 14)], context: nil).size
    }
}



public struct MenuItemText {
    let text: String
    let color: UIColor
    let selectedColor: UIColor
    let font: UIFont
    let selectedFont: UIFont
    
    public init(text: String = "Menu",
                color: UIColor = UIColor.white,
                selectedColor: UIColor = UIColor.white,
                font: UIFont = UIFont.systemFont(ofSize: 15),
                selectedFont: UIFont = UIFont.systemFont(ofSize: 16)) {
        self.text = text
        self.color = color
        self.selectedColor = selectedColor
        self.font = font
        self.selectedFont = selectedFont
        
    }
}
